package com.dao;

import com.dao.FeedbackDAO;
import com.model.Feedback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.dao.EmptyResultDataAccessException;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class FeedbackDAOImpl implements FeedbackDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 定义 SQL 语句
    private static final String SQL_FIND_ALL = "SELECT * FROM feedback";
    private static final String SQL_FIND_BY_ID = "SELECT * FROM feedback WHERE feedback_id = ?";
    private static final String SQL_FIND_BY_COURSE_ID = "SELECT * FROM feedback WHERE course_id = ?";
    private static final String SQL_INSERT = "INSERT INTO feedback (course_id, score, feedback_content) VALUES (?, ?, ?)";
    private static final String SQL_UPDATE = "UPDATE feedback SET course_id = ?, score = ?, feedback_content = ? WHERE feedback_id = ?";
    private static final String SQL_DELETE = "DELETE FROM feedback WHERE feedback_id = ?";

    private static final RowMapper<Feedback> ROW_MAPPER = (ResultSet rs, int rowNum) -> {
        Feedback feedback = new Feedback();
        feedback.setFeedbackId(rs.getInt("feedback_id"));
        feedback.setCourseId(rs.getInt("course_id"));
        feedback.setScore(rs.getInt("score"));
        feedback.setFeedbackContent(rs.getString("feedback_content"));
        return feedback;
    };

    // CRUD 方法
    /* 查找全部数据 */
    @Override
    public List<Feedback> findAll() {
        return jdbcTemplate.query(SQL_FIND_ALL, ROW_MAPPER);
    }
    /* 根据ID查找数据 */
    @Override
    public Feedback findById(Integer id) {
        try {
            return jdbcTemplate.queryForObject(SQL_FIND_BY_ID, new Object[]{id}, ROW_MAPPER);
        } catch (EmptyResultDataAccessException e) {
            return null; // 或者抛出自定义异常
        }
    }
    /* 根据课程id查找数据 */
    @Override
    public List<Feedback> findByCourseId(Integer courseId) {
        return jdbcTemplate.query(SQL_FIND_BY_COURSE_ID, new Object[]{courseId}, ROW_MAPPER);
    }
    /* 新增数据 */
    @Override
    public void save(Feedback feedback) {
        jdbcTemplate.update(SQL_INSERT,
                feedback.getCourseId(),
                feedback.getScore(),
                feedback.getFeedbackContent());
    }
    /* 更改数据 */
    @Override
    public void update(Feedback feedback) {
        jdbcTemplate.update(SQL_UPDATE,
                feedback.getCourseId(),
                feedback.getScore(),
                feedback.getFeedbackContent(),
                feedback.getFeedbackId());
    }
    /* 根据id查找数据 */
    @Override
    public void deleteById(Integer id) {
        jdbcTemplate.update(SQL_DELETE, id);
    }
}